import service from './axios'
import qs from 'qs'
import { ExtAxiosRequestOption } from '@/types/http'
import { isObject } from 'lodash'
export const get = (url: string, params?: Record<string, any>, options?: ExtAxiosRequestOption) => {
  if (params && !isObject(params)) {
    url = `${url}/${params}`
    params = undefined
  }
  return service({
    ...options,
    url,
    params,
    method: 'get'
  })
}

export const post = (url: string, data?: Record<string, any>, options?: ExtAxiosRequestOption) => {
  return service({
    ...options,
    url,
    data,
    method: 'post'
  })
}

export const put = (url: string, data?: Record<string, any>, options?: ExtAxiosRequestOption) => {
  return service({
    ...options,
    url,
    data,
    method: 'put'
  })
}

export const deleted = (url: string, id?, options?: ExtAxiosRequestOption) => {
  return service({
    ...options,
    url: `${url}/${id}`,
    method: 'delete'
  })
}

export const postForm = (
  url: string,
  data?: Record<string, any>,
  options?: ExtAxiosRequestOption
) => {
  return service({
    ...options,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    url,
    data: qs.stringify(data),
    method: 'post'
  })
}

// 上传文件
export const postFile = (
  url: string,
  data?: Record<string, any>,
  options?: ExtAxiosRequestOption
) => {
  const formData = new FormData()
  for (const key in data) {
    formData.append(key, data[key])
  }
  return service({
    ...options,
    method: 'post',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    url,
    data: formData
  })
}

// 下载文件
export const getFile = (
  url: string,
  params?: Record<string, any>,
  options?: ExtAxiosRequestOption
) => {
  return service({
    ...options,
    url,
    params,
    method: 'get',
    responseType: 'blob'
  })
}
